<?php

class ScoreManager_GroupInputController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        if ($this->getRequest()->getPost('act')=='setData')
        $this->_setData();
        $this->view->yearSemester = $this->getRequest()->getPost('yearSemester');
        $this->view->grade = $this->getRequest()->getPost('select-grade');
        if ($this->view->yearSemester and $this->view->grade)
        $this->_getSubject();
        if ($this->getRequest()->getPost('select-subject'))
        $this->_getStage();
        if ($this->getRequest()->getPost('stage_id')) {
            $this->_getStudents();
            $this->_getScores();
        }

    }

    /**
     * 設定成績
     */
    protected function _setData()
    {
        $sn = (int) $this->getRequest()->getPost('select-subject');
        $q = Doctrine_Query::create()
        ->select('subject_sn')
        ->from('Student_Model_StudentScoreElectiveGroup')
        ->where('sn=?', $sn);
        $res = $q->fetchOne();
        $subjectSn= $res->subject_sn;

        $testSort = (int)$this->getRequest()->getPost('stage_id');
        $scores = $this->getRequest()->getPost('scores');

        $teacherSn = Teacher_Model_Teacher::getSnById();
        $tempStageSn = array(); // 暫存階段代號
        foreach ($scores as $testKind => $val) {

            foreach ($val as $classScore=>$score) {
                $tempArr = explode("-", $classScore);
                $classSn = (int) $tempArr[0]; // 班級
                $studentSn = (int) $tempArr[1]; // 分數
                if (!isset($tempStageSn[$testKind][$classSn] )) {
                    // 檢查是否建立 成績主檔
                    $q = Doctrine_Query::create()
                    ->select('sn')
                    ->from('Student_Model_StudentScoreStage')
                    ->where('subject_sn=?', $subjectSn) // 科目
                    ->andWHere('class_sn=?', $classSn) // 班級
                    ->andWhere('test_kind=?',$testKind) // 成績別(平時或定期)
                    ->andWhere('test_sort=?', $testSort); // 考次
                    $res = $q->fetchOne();
                    if (!$res) {
                        $scoreStage = new Student_Model_StudentScoreStage();
                        $scoreStage->subject_sn = $subjectSn;
                        $scoreStage->class_sn = $classSn;
                        $scoreStage->test_kind = $testKind;
                        $scoreStage->test_sort = $testSort;
                        $scoreStage->teacher_sn = $teacherSn;
                        //    echo $subjectSn.'-'.$classSn.'-'.$testKind.'-'.$testSort.'<br>';
                        $scoreStage->save();
                        $tempStageSn[$testKind][$classSn] = $scoreStage->sn;
                    }
                    else
                    $tempStageSn[$testKind][$classSn] = $res->sn;

                }
                $stageSn = $tempStageSn[$testKind][$classSn];
                // 檢查成績
                $q = Doctrine_Query::create()
                ->select('sn')
                ->from('Student_Model_StudentScoreStageDetail')
                ->where('stage_sn=?', $stageSn)
                ->andWHere('student_sn=?', $studentSn);
                $res = $q->fetchOne();
                $stageDetail  = new     Student_Model_StudentScoreStageDetail();
                if (!$res) {
                    $stageDetail->stage_sn = $stageSn;
                    $stageDetail->student_sn = $studentSn;
                    $stageDetail->teacher_sn = $teacherSn;
                    if ($score==='')
                    $stageDetail->score = null;
                    else
                    $stageDetail->score = (float) $score;

                    $stageDetail->save();
                }
                else {
                    $stageDetail->assignIdentifier($res->sn);
                    $stageDetail->teacher_sn = $teacherSn;
                    if ($score==='')
                    $stageDetail->score = null;
                    else
                    $stageDetail->score = (float) $score;
                    $stageDetail->save();
                }

            }
        }
        //設為已傳送
        foreach ($tempStageSn as $val)
            foreach ($val as $sn) {
                $scoreStage = new Student_Model_StudentScoreStage();
                $scoreStage->assignIdentifier($sn);
                $scoreStage->sendmit = 'Y';
                $scoreStage->save();
            }
    }

    /**
     * 取出階段數
     */
    protected function _getStage()
    {
        $tempArr = explode('-', $this->view->yearSemester);
        $year = (int) $tempArr[0];
        $semester = (int) $tempArr[1];
        $examine = new Semester_Model_SemesterExamine();
        $examineSet = $examine->getExaminSet($year,$semester,$this->view->grade);
        $this->view->period =  $examineSet->period;
        $sn = (int) $this->getRequest()->getParam('select-subject');
        $this->view->group_sn = $sn;

        // 查詢考試設定(全學期輸入或階段輸入)
        $q = Doctrine_Query::create()
        ->select('b.scored_mode AS scored_mode')
        ->from('Student_Model_StudentScoreElectiveGroup a')
        ->leftJoin('a.Semester_Model_SemesterSubject b')
        ->where('a.sn=?', $sn);
        $this->view->scored_mode = $q->fetchOne()->scored_mode;
    }

    /**
     * 取出學科
     */
    protected  function _getSubject()
    {
        $tempArr = explode('-', $this->view->yearSemester);
        $year = (int) $tempArr[0];
        $semester = (int) $tempArr[1];
        $grade = (int) $this->view->grade;
        $q = Doctrine_Query::create()
        ->select('a.sn, a.group_name ,b.subject_sn AS subject_sn, c.name AS name, d.name AS teacher_name')
        ->from('Student_Model_StudentScoreElectiveGroup a')
        ->leftJoin('a.Semester_Model_SemesterTeacherCourse b')
        ->leftJoin('b.Semester_Model_SemesterCourse c')
        ->leftJoin('Teacher_Model_TeacherView d')
        ->where('b.year=?', $year)
        ->andWhere('b.semester=?', $semester)
        ->andWhere('b.grade=?', $grade)
        ->andWhere('b.teacher_sn=d.sn');
        //->groupBy()
        $res = $q->fetchArray();
        $arr = array();
        foreach($res as $row)
        $arr[$row['name']][$row['sn']] = $row['group_name'].' - '. $row['teacher_name'];
        if ($arr)
        $this->view->subjectSn = $row['subject_sn'];
        $this->view->subject = $arr;
    }

    /**
     * 取出學生及成績
     */
    protected  function _getStudents()
    {

        $tempArr = explode('-', $this->view->yearSemester);
        $year = (int) $tempArr[0];
        $semester = (int) $tempArr[1];
        $grade = (int) $this->view->grade;
        $sn = (int) $this->getRequest()->getParam('select-subject');
        $q = Doctrine_Query::create()
        ->select('a.*, b.sn AS student_sn, b.name AS name, b.sex AS sex,
         c.student_id AS student_id, c.number AS student_number, c.class_sn AS class_sn')
        ->from('Student_Model_StudentScoreElectiveStudent a')
        ->leftJoin('Student_Model_Student b')
        ->leftJoin('Student_Model_StudentSemester c')
        ->where('a.student_sn = b.sn')
        ->andWhere('b.sn=c.student_sn')
        ->andWHere('c.year=?', $year)
        ->andWhere('c.semester=?', $semester)
        ->andWHere('a.group_sn=?', $sn)
        ->orderBy('a.number, c.grade, c.class_sn, c.number');
        $this->view->students = $q->fetchArray();

        $this->view->stage_id = (int) $this->getRequest()->getPost('stage_id');

    }

    /**
     *  學生階段成績
     * @param integer $stage
     * @return Array
     */
    public function _getScores()
    {
        $sn = (int) $this->getRequest()->getParam('select-subject');
        $stage = (int) $this->getRequest()->getParam('stage_id');
        $this->view->stage_id = (int) $this->getRequest()->getPost('stage_id');
        $studentArr = array();
        $q = Doctrine_Query::create()
        ->select('s.student_sn, g.subject_sn AS subject_sn')
        ->from('Student_Model_StudentScoreElectiveStudent s')
        ->leftJoin('s.Student_Model_StudentScoreElectiveGroup g')
        ->where('g.sn=?',$sn );
        foreach($q->fetchArray() as $row)
        $studentArr[] = $row['student_sn'];

        $subjectSn = $row['subject_sn'];

        $q = Doctrine_Query::create()
        ->select('a.*, b.subject_sn as subject_sn, b.test_kind AS test_kind')
        ->from('Student_Model_StudentScoreStageDetail a')
        ->leftJoin('a.Student_Model_StudentScoreStage b')
        ->where('b.subject_sn=?',$subjectSn)
        ->andWhere('b.test_sort=?',$this->view->stage_id );
        $q->whereIn('a.student_sn',$studentArr);
        $res = $q->fetchArray();
        $tempArr = array();

        foreach ($res  as $row) {
            $tempArr[$row['student_sn']][$row['test_kind']] = $row['score'];
        }
        $this->view->scores = $tempArr;
    }

}

